package com.ppp.poi.common;

import com.ppp.poi.bean.result.WechatTokenResult;
import com.ppp.poi.service.HttpService;
import java.time.LocalDateTime;
import javax.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Wu Jin
 * @create 2020-02-28
 */
@Slf4j
@Component
public class WechatAccessTokenHolder {

  private static volatile String accessToken = "";

  private static volatile LocalDateTime expireTime = LocalDateTime.MIN;

  @Autowired
  private HttpService httpService;

  @Autowired
  private Parameter parameter;

  @PostConstruct
  public void init() {
    // 初始化获取AccessToken
    updateAccessToken();
  }

  /**
   * 更新获取AccessToken
   */
  public synchronized String updateAccessToken() {
    WechatTokenResult wechatTokenResult = httpService.doGetForPojo(parameter.getWechatgetAccessTokenUrl(), WechatTokenResult.class);
    if (wechatTokenResult.getErrcode() == 0) {
      accessToken = wechatTokenResult.getAccess_token();
      expireTime = LocalDateTime.now().plusHours(1).plusMinutes(30);
    }
    return accessToken;
  }

  /**
   * 获取AccessToken
   * @return
   */
  public String getAccessToken() {
    if (LocalDateTime.now().isAfter(expireTime)) {
      return updateAccessToken();
    } else {
      return accessToken;
    }
  }

}
